<template>
  <div>
    <!--    按钮头-->
    <el-card class="box-card">
      <el-row :gutter="10" class="mb8">

        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:order:add']"
          >
            添加药品
          </el-button>
        </el-col>

        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            v-hasPermi="['system:order:edit']"
          >批量设置
          </el-button>
        </el-col>

        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="addOrderAndDrug"
            v-hasPermi="['system:order:remove']"
          >暂存
          </el-button>
        </el-col>

        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-edit"
            size="mini"
            @click="handleUpdate"
            v-hasPermi="['system:order:export']"
          >提交审核
          </el-button>
        </el-col>
      </el-row>
    </el-card>
    <!--    订单表信息-->
    <el-card class="box-card">
      <el-form :inline="true" :model="form" class="demo-form-inline">
        <el-row>
          <el-form-item label="单据号">
            <el-input v-model="form.orderDocumentId" placeholder="单据号" readonly></el-input>
          </el-form-item>
          <el-form-item label="申请人">
            <el-input v-model="form.orderMan" placeholder="申请人" readonly></el-input>
          </el-form-item>

          <el-form-item label="供应商">
            <el-select v-model="form.orderSupId" placeholder="请选择供应商">
              <el-option
                v-for="dict in dict.type.durg_support_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="申请时间">
            <el-date-picker type="date" placeholder="选择日期" v-model="form.createTime"
                            style="width: 100%;" readonly></el-date-picker>
          </el-form-item>
          <el-form-item label="总批发额">
            <el-input v-model="form.orderTotal" placeholder="0" readonly></el-input>
          </el-form-item>
        </el-row>
      </el-form>
    </el-card>

    <!--    表格页面-->

    <el-card class="box-card">
      <el-table v-loading="loading" :data="detailList">
        <el-table-column label="药品ID" align="center" prop="detailDrugId"/>
        <el-table-column label="药品名称" align="center" prop="detailDrugName"/>
        <el-table-column label="规格" align="center" prop="detailNorms"/>
        <el-table-column label="生产厂家" align="center" prop="detailProduceId" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.durg_producer_status" :value="scope.row.detailProduceId"/>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="detailDrugNum">
          <template slot-scope="scope">
            <el-input-number controls-position="right" :min="0" @change="numberChange(scope.$index,scope.row)"
                             v-model="scope.row.detailDrugNum" style="width: 120px"/>
          </template>
        </el-table-column>
        <el-table-column label="批发单价" align="center" prop="detailDrugPrice"/>
        <el-table-column label="批发额" align="center" prop="detailTotalPrice"/>
        <el-table-column label="批次号" align="center" prop="detailBathNum"/>
        <el-table-column label="备注" align="center" prop="detailRemarks"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:detail:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"/>

      <!-- 添加或修改订单明细对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="1050px" append-to-body center>
        <!--表单页面-->
        <el-form :model="queryDrugParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
          <el-form-item label="关键字" prop="durgCode">
            <el-input
              v-model="queryDrugParams.durgCode"
              placeholder="请输入关键字"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="药品类型" prop="durgType">
            <el-select v-model="queryDrugParams.durgType" placeholder="药品类型" clearable>
              <el-option
                v-for="dict in dict.type.drug_durg_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="处方类型" prop="durgOtcType">
            <el-select v-model="queryDrugParams.durgOtcType" placeholder="处方类型" clearable>
              <el-option
                v-for="dict in dict.type.durg_otc_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>

        </el-form>
        <el-table v-loading="drugLoading" :data="durgList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="药品ID" align="center" prop="durgId"/>
          <el-table-column label="药品名称" align="center" prop="durgName"/>
          <el-table-column label="药品编码" align="center" prop="durgCode"/>
          <el-table-column label="生产厂家" align="center" prop="durgProducer" width="100">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.durg_producer_status" :value="scope.row.durgProducer"/>
            </template>
          </el-table-column>
          <el-table-column label="药品类型" align="center" prop="durgType"/>
          <el-table-column label="处方类型" align="center" prop="durgOtcType"/>
        </el-table>

        <pagination
          v-show="durgTotal>0"
          :total="durgTotal"
          :page.sync="queryDrugParams.pageNum"
          :limit.sync="queryDrugParams.pageSize"
          @pagination="getDrugList"/>

        <!--按钮开关-->
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">添 加</el-button>
          <el-button @click="cancel">关 闭</el-button>
        </div>
      </el-dialog>
    </el-card>


  </div>
</template>

<script>
import {listDetail, getDetail, delDetail, addDetail, updateDetail, addOrderDetail} from "@/api/drug/detail";
import {listDurg, getDurg, delDurg, addDurg, updateDurg} from "@/api/drug/drug";
import {listOrder, getOrder, delOrder, addOrder, updateOrder} from "@/api/drug/order";
import Cookies from "js-cookie";


export default {
  name: "Detail",
  dicts: ['durg_support_type', 'durg_order_status', 'drug_durg_type', 'durg_otc_type', 'durg_producer_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      //药品遮罩层
      drugLoading: false,
      // 选中药品ID数组
      ids: [],
      //被选中的状态信息
      detailStatuses: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //药品总条数
      durgTotal: 0,
      // 订单明细表格数据
      detailList: [],
      // 药品表格数据
      durgList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        detailProduceId: null,
        detailDrugId: null,
        orderId: null,
        detailDrugNum: null,
        detailDrugPrice: null,
        detailBathNum: null,
        detailTotalPrice: null,
        detailRemarks: null,
        detailNorms: null,
        detailDrugName: null
      },
      queryDrugParams: {
        pageNum: 1,
        pageSize: 10,
        durgName: null,
        durgCode: null,
        durgProducer: null,
        durgType: null,
        durgOtcType: null,
        durgUnit: null,
        durgOtcPrice: null,
        durgNumber: null,
        durgNumberMin: null,
        durgConvert: null,
        durgStatus: null,
      },
      // 表单参数
      form: {
        orderDocumentId: null,
        orderMan: null,
        orderSupId: null,
        createTime: null,
        orderTotal: 0,
        detailStatus: 0,
        orderId: null,
        createBy: null
      },
      // 表单校验
      rules: {},
      //订单表id
      orderId: null,
    };
  },
  created() {
    //获取传递参数信息
    this.orderId = this.$route.params.orderId;
    if (this.orderId !== null && this.orderId !== undefined) {
      //修改页面
      this.queryParams.orderId = this.orderId
      this.getList();
    } else {
      //新增页面
      this.getUserAndDocumentNumber()
      this.loading = false;
    }
  },
  methods: {
    /** 查询订单明细列表 */
    getList() {
      this.getOrder();
      this.getListDetail();
    },
    /** 查询订单表信息 */
    getOrder() {
      this.loading = true;
      getOrder(this.orderId).then(response => {
        this.form = response.data
        this.loading = false;
      })
    },
    /** 查询订单明细 */
    getListDetail() {
      let _this = this
      listDetail(this.queryParams).then(response => {
        this.detailList = response.rows;
        this.total = response.total;
        _this.totalAmount()
      });
    },

    /** 查询药品列表 */
    getDrugList() {
      this.drugLoading = true;
      listDurg(this.queryDrugParams).then(response => {
        this.durgList = response.rows;
        this.durgTotal = response.total;
        this.drugLoading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        detailId: null,
        detailProduceId: null,
        detailDrugId: null,
        orderId: null,
        detailDrugNum: null,
        detailDrugPrice: null,
        detailBathNum: null,
        detailTotalPrice: null,
        detailRemarks: null,
        detailNorms: null,
        orderTotal: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryDrugParams.pageNum = 1;
      this.getDrugList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.durgId)
      this.detailStatuses = selection.map(item => item.detailStatus)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.title = "添加药品信息";
      this.getDrugList();
    },
    /** 提交按钮 */
    submitForm() {
      if (this.orderId !== null && this.orderId !== undefined) {
        addOrderDetail(this.ids, this.orderId).then(response => {
          this.$modal.msgSuccess("添加成功");
          this.queryParams.orderId = this.orderId
          this.open = false;
          this.getList();
        })
      }

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const detailIds = row.detailId || this.ids;
      this.$modal.confirm('是否确认删除订单明细编号为"' + detailIds + '"的数据项？').then(function () {
        return delDetail(detailIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /* 数量发生改变操作-改变表单中总金额*/
    numberChange(index, row) {
      let detailId = row.detailId
      let detailDrugNum = row.detailDrugNum
      let detailTotalPrice = detailDrugNum * row.detailDrugPrice
      this.loading = true;
      //发送修改请求
      updateDetail({
        detailId: detailId,
        detailDrugNum: detailDrugNum,
        detailTotalPrice: detailTotalPrice
      }).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.getListDetail();
        this.loading = false;
      });
    },
    /**获取用户信息和随机生成单据号并保存单据号信息*/
    getUserAndDocumentNumber() {
      const username = Cookies.get("username");
      let result = "CG";
      //随机生成0-9的数字 生成8个
      for (let i = 0; i < 8; i++) {
        let random = Math.floor(Math.random() * 10)
        result += random;
      }
      this.form.orderMan = username;
      this.form.createBy = username;
      this.form.orderDocumentId = result;
      //新增采购单信息
      addOrder(this.form).then(response => {
        this.$modal.msgSuccess("创建采购单成功");
        this.orderId = response
      });

    },
    /*保存单据信息*/
    addOrderAndDrug() {
      this.form.orderId = this.orderId
      updateOrder(this.form).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.$router.push(`/drug/order`)
      });
    },
    /** 提交审核按钮操作 */
    handleUpdate() {
      const orderId = this.orderId
      let detailStatus = "";
      getOrder(orderId).then(response=>{
        detailStatus = response.detailStatus;
      })

      if (detailStatus !== "0") {
        this.$modal.msgError("只允许选择申请状态提交审核!");
        return
      }
      updateOrder({orderId: orderId, detailStatus: 1}).then(response => {
        this.$modal.msgSuccess("申请审核成功!");
        this.$router.push(`/drug/order`)
      });
    },
    /*计算总金额信息*/
    totalAmount() {
      let result = 0;
      this.detailList.forEach(data => {
        result += data.detailTotalPrice
      })
      this.form.orderTotal = result;
    }
  }
};
</script>

<style scoped>
.box-card {
  margin-top: 15px;
  margin-left: 20px;
  margin-right: 20px;
}

.el-col {
  margin-right: 10px;
}

/deep/ .el-form-item__content {
  width: 180px !important;
}
</style>
